﻿Imports System.Data.SqlClient
Public Class frmThemKhachHang
    Dim themmoi As Boolean
    Public thanhcong As Boolean = False
    Private Sub frmThemKhachHang_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        CapNhatLuoi()
    End Sub

    Private Sub CapNhatLuoi()
        Dim strSql As String = "select ROW_NUMBER() OVER (ORDER BY maKH) as STT, maKH as [Mã khách hàng], tenkh as [Tên khách hàng], diachi as [Địa chỉ], sodt as [Số điện thoại], masothue as [Mã số thuế], tknganhang as [TK Ngân hàng] from KhachHang "
        Dim myConn As New SqlConnection(modKetNoi.strConnectionString)
        Dim myTable As New DataTable
        Try
            myConn.Open()
            strSql &= " order by STT"
            Dim myAdapter As New SqlDataAdapter(strSql, myConn)
            myAdapter.Fill(myTable)
            dgvList.DataSource = myTable
            dgvList.Columns.Item(0).Width = 50
            dgvList.Columns.Item(1).Width = 120
            dgvList.Columns.Item(2).Width = 200
            dgvList.Columns.Item(3).Width = 300
            dgvList.Columns.Item(4).Width = 150
            dgvList.Columns.Item(5).Width = 150
            dgvList.Columns.Item(6).Width = 150

        Catch ex As Exception

        End Try
        myConn.Close()
        myConn.Dispose()
    End Sub

    Private Function DeleteData(ByVal MaKH As String) As Boolean
        Dim strSql As String = "Delete from KhachHang where MaKH = @MaKH"
        Dim myConn As New SqlConnection(modKetNoi.strConnectionString)
        Dim myComm As New SqlCommand
        Dim result As Boolean = True
        Try
            myConn.Open()
            myComm.Connection = myConn
            myComm.CommandText = strSql
            myComm.Parameters.AddWithValue("@MaKH", MaKH)
            myComm.ExecuteNonQuery()
        Catch ex As Exception
            result = False
        End Try
        myConn.Close()
        myConn.Dispose()
        Return result
    End Function

    Private Sub dgvList_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvList.KeyDown
        If e.KeyCode = Keys.Delete Then
            If Me.dgvList.SelectedRows.Count > 0 Then
                If MsgBox("Xóa Khách hàng đã chọn?", MsgBoxStyle.OkCancel, "Xác nhận") = MsgBoxResult.Ok Then
                    If DeleteData(Me.dgvList.SelectedRows.Item(0).Cells(1).Value) Then
                        CapNhatLuoi()
                    Else
                        MsgBox("Lỗi xóa dữ liệu!")
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub dgvList_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvList.SelectionChanged
        If dgvList.SelectedRows.Count > 0 Then
            txtMaKH.Text = dgvList.SelectedRows(0).Cells(1).Value.ToString()
            txtTenKH.Text = dgvList.SelectedRows(0).Cells(2).Value.ToString()
            txtDiaChi.Text = dgvList.SelectedRows(0).Cells(3).Value.ToString()
            txtSoDt.Text = dgvList.SelectedRows(0).Cells(4).Value.ToString()
            txtMSThue.Text = dgvList.SelectedRows(0).Cells(5).Value.ToString()
            txtTKNganHang.Text = dgvList.SelectedRows(0).Cells(6).Value.ToString()
        End If
    End Sub

    Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click
        txtMaKH.Text = ""
        txtTenKH.Text = ""
        txtDiaChi.Text = ""
        txtSoDt.Text = ""
        txtMSThue.Text = ""
        txtTKNganHang.Text = ""
        txtMaKH.ReadOnly = False
        txtTenKH.ReadOnly = False
        txtDiaChi.ReadOnly = False
        txtSoDt.ReadOnly = False
        txtMSThue.ReadOnly = False
        txtTKNganHang.ReadOnly = False
        btnLuu.Enabled = True
        btnSua.Enabled = False
        themmoi = True
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If Me.dgvList.SelectedRows.Count > 0 Then
            If MsgBox("Xóa khách hàng đã chọn?", MsgBoxStyle.OkCancel, "Xác nhận") = MsgBoxResult.Ok Then
                If DeleteData(Me.dgvList.SelectedRows.Item(0).Cells(1).Value) Then
                    CapNhatLuoi()
                Else
                    MsgBox("Lỗi xóa dữ liệu!")
                End If
            End If
        Else
            MsgBox("Vui lòng chọn dòng cần Xóa!")
        End If
    End Sub

    Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click
        txtTenKH.ReadOnly = False
        txtDiaChi.ReadOnly = False
        txtSoDt.ReadOnly = False
        txtMSThue.ReadOnly = False
        txtTKNganHang.ReadOnly = False
        btnLuu.Enabled = True
        themmoi = False
    End Sub

    Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click
        Me.Close()
    End Sub

    Private Sub btnDauTien_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDauTien.Click
        diChuyenChon(1)
    End Sub

    Private Sub btnTruoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTruoc.Click
        diChuyenChon(2)
    End Sub

    Private Sub btnSau_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSau.Click
        diChuyenChon(3)
    End Sub

    Private Sub btnCuoiCung_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCuoiCung.Click
        diChuyenChon(4)
    End Sub

    Private Sub diChuyenChon(ByVal kind As Integer)
        If dgvList.Rows.Count > 0 Then
            Dim curIndex As Integer = 0
            If dgvList.CurrentRow IsNot Nothing Then
                curIndex = dgvList.CurrentRow.Index
            End If
            Select Case kind
                Case 1
                    curIndex = 0
                Case 2
                    If curIndex > 0 Then
                        curIndex = curIndex - 1
                    End If
                Case 3
                    If curIndex <> dgvList.Rows.Count - 1 Then
                        curIndex = curIndex + 1
                    End If
                Case 4
                    curIndex = dgvList.Rows.Count - 1
            End Select
            dgvList.CurrentCell = dgvList.Item(0, curIndex)
        End If
    End Sub

    Private Sub btnKhongLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnKhongLuu.Click
        HuyBo()
        If dgvList.SelectedRows.Count > 0 Then
            txtMaKH.Text = dgvList.SelectedRows(0).Cells(1).Value.ToString()
            txtTenKH.Text = dgvList.SelectedRows(0).Cells(2).Value.ToString()
            txtDiaChi.Text = dgvList.SelectedRows(0).Cells(3).Value.ToString()
            txtSoDt.Text = dgvList.SelectedRows(0).Cells(4).Value.ToString()
            txtMSThue.Text = dgvList.SelectedRows(0).Cells(5).Value.ToString()
            txtTKNganHang.Text = dgvList.SelectedRows(0).Cells(6).Value.ToString()
        End If
    End Sub

    Private Sub HuyBo()
        txtMaKH.ReadOnly = True
        txtTenKH.ReadOnly = True
        txtDiaChi.ReadOnly = True
        txtSoDt.ReadOnly = True
        txtMSThue.ReadOnly = True
        txtTKNganHang.ReadOnly = True
        btnLuu.Enabled = False
        btnSua.Enabled = True
    End Sub

    Private Sub btnLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLuu.Click
        If validateInput() Then
            If CapNhat() Then
                thanhcong = True
                MsgBox("Lưu thành công")
                CapNhatLuoi()
                If themmoi Then
                    txtMaKH.Text = ""
                    txtTenKH.Text = ""
                    txtDiaChi.Text = ""
                    txtSoDt.Text = ""
                    txtMSThue.Text = ""
                    txtTKNganHang.Text = ""
                Else
                    HuyBo()
                End If
            Else
                MsgBox("Lưu thất bại")
            End If
        End If
    End Sub

    Private Function CapNhat() As Boolean
        Dim strSql As String = ""
        Dim myConn As New SqlConnection(modKetNoi.strConnectionString)
        Dim myComm As New SqlCommand
        Dim result As Boolean = True
        Try
            myConn.Open()
            myComm.Connection = myConn
            If themmoi Then
                strSql = "Insert into KhachHang(MaKH, TenKH, DiaChi, SoDT, MaSoThue, TKNganHang) values (@MaKH, @TenKH, @DiaChi, @SoDT, @MaSoThue, @TKNganHang)"
            Else
                strSql = "Update KhachHang set TenKH = @TenKH, DiaChi = @DiaChi, SoDT = @SoDT, MaSoThue = @MaSoThue, TKNganHang = @TKNganHang where MaKH = @MaKH"
            End If
            myComm.CommandText = strSql
            myComm.Parameters.AddWithValue("@MaKH", txtMaKH.Text.Trim())
            myComm.Parameters.AddWithValue("@TenKH", txtTenKH.Text.Trim())
            myComm.Parameters.AddWithValue("@DiaChi", txtDiaChi.Text.Trim())
            myComm.Parameters.AddWithValue("@SoDT", getEmptyValue(txtSoDt.Text))
            myComm.Parameters.AddWithValue("@MaSoThue", getEmptyValue(txtMSThue.Text))
            myComm.Parameters.AddWithValue("@TKNganHang", getEmptyValue(txtTKNganHang.Text))
            myComm.ExecuteNonQuery()
        Catch ex As Exception
            result = False
        End Try
        myConn.Close()
        myConn.Dispose()
        Return result
    End Function

    Private Function checkExist(ByVal MaKH As String) As Boolean
        Dim strSql As String = "Select count(*) from KhachHang where MaKH = @MaKH"
        Dim myConn As New SqlConnection(modKetNoi.strConnectionString)
        Dim myComm As New SqlCommand
        Dim result As Boolean = False
        Try
            myConn.Open()
            myComm.CommandText = strSql
            myComm.Parameters.AddWithValue("@MaKH", MaKH)
            myComm.Connection = myConn
            If myComm.ExecuteScalar() > 0 Then
                result = True
            End If
        Catch ex As Exception

        End Try
        myConn.Close()
        myConn.Dispose()
        Return result
    End Function

    Private Function validateInput() As Boolean
        If Me.txtMaKH.Text.Trim = "" Then
            MsgBox("Mã khách hàng không thể rỗng.", MsgBoxStyle.Information)
            txtMaKH.Focus()
            Return False
        Else
            If checkExist(Me.txtMaKH.Text.Trim) Then
                If themmoi Then
                    MsgBox("Mã khách hàng đã tồn tại", MsgBoxStyle.Information)
                    txtMaKH.Focus()
                    Return False
                End If
            ElseIf Not themmoi Then
                MsgBox("Mã khách hàng chưa tồn tại", MsgBoxStyle.Information)
                txtMaKH.Focus()
                Return False
            End If
        End If

        If Me.txtTenKH.Text.Trim = "" Then
            MsgBox("Tên khách hàng không thể rỗng.", MsgBoxStyle.Information)
            txtTenKH.Focus()
            Return False
        End If

        If Me.txtDiaChi.Text.Trim = "" Then
            MsgBox("Địa chỉ không thể rỗng.", MsgBoxStyle.Information)
            txtDiaChi.Focus()
            Return False
        End If

        Return True
    End Function

    Function getEmptyValue(ByVal value As String) As String
        If value.Trim = "" Then
            Return ""
        End If
        Return value.Trim
    End Function
End Class